using System;
using Microsoft.SPOT;

namespace Gadgeteer.Modules.Community.XBee
{
    /// <summary>
    /// Converts byte arrays to numbers, and numbers to byte arrays
    /// </summary>
    public static class Converter
    {
        /// <summary>
        /// Convert a byte array to uint
        /// </summary>
        /// <param name="input">byte array representing a number that is 32 bits</param>
        /// <returns>32 bit unsigned integer</returns>
        public static uint ToUInt(byte[] input)
        {
            uint result = 0;
            for (int i = 0; i < input.Length; i++)
            {
                result += (uint)(input[i] << 8 * (input.Length - 1 - i));
            }

            return result;
        }

        /// <summary>
        /// Convert a byte array to ushort
        /// </summary>
        /// <param name="input">byte array representing a number that is 16 bits or less</param>
        /// <returns>a 16 bit unsigned integer</returns>
        public static ushort ToUShort(byte[] input)
        {
            ushort result = 0;
            for (int i = 0; i < input.Length; i++)
            {
                result += (ushort)(input[i] << 8 * (input.Length - 1 -i));
            }

            return result;
        }

        /// <summary>
        /// Converts a ushort to a byte array
        /// </summary>
        /// <param name="input">ushort</param>
        /// <returns>byte array of length 2</returns>
        public static byte[] ToByteArray(ushort input)
        {
            byte[] result = new byte[2];

            for (int i = 1; i >= 0; i--)
            {
                result[i] = (byte)input;
                input >>= 8;
            }
            return result;
        }

        /// <summary>
        /// converts an unsigned int to a byte array
        /// </summary>
        /// <param name="input">unsigned int</param>
        /// <returns>byte array of length 4</returns>
        public static byte[] ToByteArray(uint input)
        {
            byte[] result = new byte[4];

            for (int i = 3; i >= 0; i--)
            {
                result[i] = (byte)input;
                input >>= 8;
            }
            return result;
        }

    }
}
